﻿using System.IO;
using System.Web;

namespace netaddICTs.Umb.ProtectedMedia.Business.IO {
 
    public abstract class StorageImpl {
    
        protected const string PathSeparator = @"\";

        protected StorageImpl(string path) {
            Path = path;
        }

        protected string Path { get; set; }

        protected static bool Create(string directory, HttpPostedFile postedFile) {
            var filenameOnDisk = string.Concat(directory, PathSeparator, System.IO.Path.GetFileName(postedFile.FileName));

            try {
                Directory.CreateDirectory(directory);
                postedFile.SaveAs(filenameOnDisk);
                return true;
            } catch {
                return false;
            }
        }

        protected static bool Delete(string directory) {

            if (Directory.Exists(directory)) {
                var fileNames = Directory.GetFiles(directory);

                foreach (var fileName in fileNames)
                    File.Delete(fileName);

                Directory.Delete(directory);
            }

            return true;
        }

        public virtual long CalculateBytes(string filename) {
            try {
                var fileInfo = new FileInfo(filename);

                return fileInfo.Length;
            } catch {
                return 0;
            }
        }

        public virtual string BuildFilename(int mediaNodeId, string filename) {
            return string.Concat(Path, PathSeparator, mediaNodeId, PathSeparator, filename);
        }
    }
}